let hogan = require('hogan.js');
// require('blueimp-file-upload/css/jquery.fileupload.css');
// require('blueimp-file-upload/css/jquery.fileupload-ui.css');

/* The jQuery UI widget factory, can be omitted if jQuery UI is already included */
// require('jquery-ui/ui/widget');
// require('blueimp-file-upload/js/jquery.iframe-transport.js');
// require('blueimp-file-upload/js/jquery.fileupload.js');
// require('load-image');
// require('canvas-to-blob');
// require('blueimp-file-upload/js/jquery.fileupload-process.js');
// require('blueimp-file-upload/js/jquery.fileupload-image.js');


let util = {
    data: {
        fileList: []
    },
    getServerUrl: function () {
        let loc = window.location,
            protocal = loc.protocol,
            host = loc.host,
            hostName = loc.hostname,
            port = loc.port,
            pathName = loc.pathname
        return protocal + '//' + host;
    },
    getElementById: function (DOMID) {
        return document.getElementById(DOMID) || null;
    },
    renderHtml: function (htmlTemplate, data) {

        let newTemplate = hogan.compile(htmlTemplate),
            result = newTemplate.render(data);

        return result;
    },
    //网络请求
    request: function (param) {
        var _this = this;
        $.ajax({
            method: param.method,
            url: param.url || '',
            dataType: param.type || 'json',
            cache: param.cache,
            contentType: param.contentType,
            data: param.data || '',
            processData: param.processData,
            xhr: param.xhr,
            success: function (res) {
                //请求成功
                typeof param.success === 'function' && param.success(res);
            },
            error: function (err) {
                typeof param.error === 'function' && param.error(err.statusText);
            }
        })
    },
    //图片上传
    uploadFile: function (params) {

        let $tableRow = params.$tableRow || [],
            selector = params.selector,
            _this = this;

        //清空上传列表
        _this.data.fileList = [];

        if (!selector || !(selector instanceof jQuery)) {
            alert('上传selector，不存在')
        }

        selector.fileupload({
            dataType: 'json',
            url: params.url || '',
            type: params.type || 'POST',
            autoUpload: false,
            disableImageResize: /Android(?!.*Chrome)|Opera/
                .test(window.navigator && navigator.userAgent),
            previewMaxWidth: 100,
            previewMaxHeight: 100,
            previewCrop: true,
            sequentialUploads: true,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png|xls|xlsx)$/i,
            formData: $('form').serializeArray()
        })
            .on('fileuploadadd', function (e, data) {

                data.context = $('<tr/>').appendTo('#upload-table > tbody');

                $("#btn-start").off('click').on('click', function () {
                    $(this).text('上传中...').addClass('disabled')
                    selector.find('tr > td .cancel-upload').addClass('disabled');
                    selector.fileupload('send', { files: _this.data.fileList });
                });

                $.each(data.files, function (index, file) {
                    let size = file.size / 1024 / 1024;

                    _this.data.fileList.push(file);

                    $('<td/>', {
                        'class': 'text-center',
                        text: file.name
                    }).appendTo(data.context);

                    ($('<textarea/>', {
                        'class': 'image-ps',
                        rows: 3,
                        name: "credentials"
                        // name: 'image-info'
                    }).appendTo($('<td/>', {
                        'class': 'text-center'
                    }).appendTo(data.context)
                        ));

                    $('<input/>', {
                        type: 'date',
                        class: 'form-control'
                    }).appendTo($('<td/>', {
                        'class': "text-center"
                    }).appendTo(data.context))


                    $('<td/>', {
                        'class': 'text-center',
                        text: `${Number.parseFloat(size).toFixed(2)}M`
                    }).appendTo(data.context);

                    ($('<textarea/>', {
                        'class': 'image-ps',
                        rows: 3,
                        name: 'remark',
                        // name: 'ps'
                    }).appendTo($('<td/>', {
                        'class': 'text-center'
                    }).appendTo(data.context)
                        ));

                    let button_wrapper = $('<td/>', {
                        "class": 'text-center'
                    })

                    // $('<button/>', {
                    //     text: '上传',
                    //     "class": "btn btn-primary  start-upload",
                    //     click: function (e) {
                    //         e.preventDefault();
                    //         $(this).text('上传中...').addClass('disabled')
                    //         data.process().done(function () {
                    //             data.submit();
                    //         });
                    //     }
                    // })
                    // .prepend('<i class="fa fa-upload"></i> ')
                    // .appendTo(button_wrapper)

                    $('<button/>', {
                        text: '撤销',
                        "class": "btn btn-danger cancel-upload",
                        click: function (e) {
                            $(this).parents('tr').remove();
                        }
                    })
                        .prepend('<i class="fa fa-times"></i> ')
                        .appendTo(button_wrapper)

                    button_wrapper.appendTo(data.context);
                });
            })
            .on('fileuploadprocessalways', function (e, data) {

                var index = data.index,
                    file = data.files[index],
                    node = $(data.context.children()[index]);

                if (file.preview) {

                    $('<td/>', {
                        'class': 'text-center'
                    })
                        .prependTo(data.context)
                        .append(file.preview);


                }
                if (file.error) {
                    node
                        .append($('<span class="text-danger"/>').text(file.error));
                }

            })
            .on('fileuploadprogressall', function (e, data) {
                let total = Number.parseFloat(data.total / 1024 / 1024).toFixed(2),
                    loaded = Number.parseFloat(data.loaded / 1024 / 1024).toFixed(2),
                    progress = parseInt(data.loaded / data.total * 100, 10)

                $('.fileupload-progress').addClass('in')
                $('#progress').css(
                    'width',
                    progress + '%'
                ).html(`${loaded} MB / ${total} MB | ${progress} %`);
                // $("#progress-extend").text(`${loaded} MB/${total} MB | ${progress} %`)
            })
            .on('fileuploadfail', function (e, data) {
                $.each(data.files, function (index) {
                    var error = $('<span class="text-danger"/>').text('File upload failed.');
                });
            })
            .on('fileuploaddone', function (e, data) {
                $.each(data.files, function (index, file) {
                    if (file.error) {
                        var error = $('<span class="text-danger"/>').text(file.error);
                        $(data.context.children()[index])
                            .append('<br>')
                            .append(error);
                    }
                    console.log(`${file.name}上传成功!`);
                });
                console.log(`全部上传成功!`);
                $("#btn-start").html("<i class='fa fa-upload'></i> 开始上传").removeClass('disabled');
                // selector.find('tr > td .cancel-upload').parent().remove();
            })
    },
    //格式化表头字段
    formatFields: function (fields) {
        let formattedArray = [],
            keys = Object.keys(fields);

        $.each(keys, (index, loopValue) => {
            let newObj = {
                field: loopValue,
                title: fields[loopValue],
                align: 'center',
            };
            if (loopValue === 'documents') {
                newObj.formatter = function (value, row) {
                    return `<a href="#" data-fileId="${row.id}" class="jsOpenImageModal">点击查看</a>`;
                }
            }
            if (loopValue === 'opera') {
                newObj.formatter = function (value, row) {
                    return `
                        <a href="#" class="jsAddToTrash opera" data-fileId="${row.id}" style="color:red" title="放置回收站">
                            <i class="fa fa-trash"></i>
                        </a>
                        `
                }
            }
            formattedArray.push(newObj);
        })
        return formattedArray;
    },
    //渲染数据表格
    renderTable: function (params) {
        let $selector = params.selector,
            formattedFields = this.formatFields(params.fields),
            _this = this;

        if (!$selector || !($selector instanceof jQuery)) {
            return;
        }

        $selector.bootstrapTable({
            url: params.url,
            columns: formattedFields,
            striped: true,
            sidePagination: "server",
            pagination: true,
            search: false,
            searchAlign: 'left',
            showRefresh: params.showRefresh,
            paginationVAlign: 'bottom',
            paginationHAlign: 'right',
            smartDisplay: false,
            clickToSelect: true,
            toolbar: '#toolbar',
            toolbarAlign: 'left',
            pageList: params.pageList || [10, 20, 30],
            method: 'GET',
            queryParamsType: "undefined",
            responseHandler: function (res) {
                let result = res.result,
                    totalElements = result.totalElements,
                    rows = result.content;
                return {
                    total: totalElements,
                    rows: params.formatterData(rows)
                }
            },
            queryParams: function queryParams(params) {   //设置查询参数  
                var param = {
                    pageNumber: params.pageNumber,
                    pageSize: params.pageSize,
                    searchText: params.searchText,
                    sortName: params.sortName,
                    sortOrder: params.sortOrder,
                    searchKey: $('#keyword').val()
                };
                return param;
            },
            dataType: 'json',
            onRefresh: function (e) {
                let keyword = $(e.currentTarget)
                    .parent()
                    .siblings('div.search')
                    .find('input')
                    .val()

                $(this).bootstrapTable('refresh', { url: params.url });
            }
        })
    },
    //销毁表格
    destoryTable: function ($selector) {
        if (!$selector || !($selector instanceof jQuery)) {
            console.log('$selector is not a jquery object');
        }
        $selector.bootstrapTable('destroy');
    },
    uploadFile: function (params) {
        $.ajax({
            url: 'http://localhost:3000/uploads/',
            method: 'POST',
            data: params.formData,
            cache: false,
            processData: false,
            contentType: false,
            success: function (res) {
                params.success();
            },
            error: function (err) {
                console.log(err);
            }
        })
    }

}

module.exports = util;